import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { format, formatDistance, formatRelative, subDays } from 'date-fns';

import { defalutImg } from '../../comm';
import { gameBannerStatusArrs } from '../../status.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { GameOperateManageService } from '../game-operate-manage.service';
import { GameManageService } from '../../game-manage/game-manage.service';

@Component({
  selector: 'app-game-operate-banner',
  templateUrl: './game-operate-banner.component.html',
  styleUrls: ['./game-operate-banner.component.scss']
})
export class GameOperateBannerComponent implements OnInit {

  fallback: string = defalutImg;
  searchOptions = [
    {
      type: 2,
      labelText: '状态',
      valueKey: 'state',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...gameBannerStatusArrs],
    }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  /**
   * 新增 | 编辑 Modal
   * ----------------------------------------------------------------
   */
  isVisible: boolean = false;
  submitLoading: boolean = false;
  modalItem: any = null;
  validateForm!: FormGroup;

  gameAppOptions: any = []; // 应用Options

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private commonService: CommonService,
    private gameManageService: GameManageService,
    private services: GameOperateManageService
  ) { }

  ngOnInit(): void {
    this.loadAppOptionsData();

    this.validateForm = this.fb.group({
      word: ['', [Validators.required]], // 名称
      picUrl: ['', [Validators.required]], // 图片
      linkType: ['', [Validators.required]], // 跳转方式 1：游戏ID 2：链接地址
      linkUrl: ['', [Validators.required]], // 游戏ID
      beginTime: ['', [Validators.required]], // 开始时间
      endTime: ['', [Validators.required]], // 结束时间
      bak: [''] // 备注
    });
  }

  // 查询游戏应用
  async loadAppOptionsData() {
    let params = {
      page: 1,
      pageSize: 10000
    }
    const {code, data}: any = await this.gameManageService.gameTableData(params);
    if (code === 0) {
      this.gameAppOptions = data.records || [];
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getGameBannerListData(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * 新增 | 编辑 Modal
   * ----------------------------------------------------------------
   */
  showEditModal(item?: any) {
    this.validateForm.reset();
    this.modalItem = null;

    // 编辑
    if (item) {
      this.modalItem = item;
      this.validateForm.patchValue({
        word: item.word, // 名称
        picUrl: item.picUrl || '', // 图片
        linkType: item.linkType, // 跳转方式 1：游戏 2：链接
        linkUrl: item.linkType === 1 ? Number(item.linkUrl) : item.linkUrl, // 游戏ID | 链接
        beginTime: item.beginTime || '', // 开始时间
        endTime: item.endTime || '', // 结束时间
        bak: item.bak || '' // 备注
      })
    }
    this.isVisible = true;
  }

  async submitForm() {
    if (this.validateForm.valid) {
      let params = {
        ...this.validateForm.value
      }
      if (this.modalItem) {
        params.id = this.modalItem.id
      }
      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          params[key] = '';
        }
      }
      this.submitLoading = true;
      const {code, data, message}: any = await this.services.updateGameBannerData(params);
      this.submitLoading = false;

      if (code === 0) {
        this.msg.success('操作成功');
        this.loadTable();
        this.isVisible = false;
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 上1 下2 移动
   * @param item 
   * @param type 
   */
  async moveItemData(item: any, type: number) {
    let params = {
      id: item.id,
      moveType: type
    }
    const {code, data, message}: any = await this.services.moveGameBannerData(params);

    if (code === 0) {
      this.msg.success('操作成功');
      this.loadTable();
    }
  }

  // 删除
  async deleteItemData(item: any) {
    const {code, data, message}: any = await this.services.deleteGameBannerData(item.id);

    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  // 上下移动 Disabled
  setMoveDisabled(index: number, type: number) {
    let currIndex = this.tableParams.pageSize * (this.tableParams.page - 1) + index + 1;

    if (type === 1) {
      // 上移
      if (currIndex === 1) {
        return true;
      } else {
        return false;
      }
    } else {
      // 下移
      if (currIndex === this.tableParams.total) {
        return true;
      } else {
        return false;
      }
    }
  }

  timeChange(val: any, key: string) {
    let timeVal = val ? format(new Date(val), 'yyyy-MM-dd HH:mm:ss') : null;
    this.validateForm.get(key)?.setValue(timeVal);
  }

  gameTypeChange(val: any) {
    if (val == 1) {
      this.validateForm.get('linkUrl')?.setValue('');
    }
  }
}
